﻿/**********************************************************
 ●项目：Smartkernel
 ●公司：智能核心信息技术研发中心
 ●作者：曹艳白
 ●邮箱：caoyanbai@gmail.com
 ●创建：2008-08-10
**********************************************************/
using System;
using System.Diagnostics;

namespace Smartkernel
{
    /// <summary>
    /// 智能行为操作类，封装对委托，函数调用等相关的功能
    /// </summary>
    public static class SmartAction
    {
        /// <summary>
        /// 判断委托调用是不是会引发异常
        /// </summary>
        /// <param name="action">需要调用的无参函数</param>
        /// <returns>调用的结果，true代表引发了异常，false则相反</returns>
        public static bool IsInvokeFail(Action action)
        {
            bool isInvokeFail = false;
            try
            {
                action.Invoke();
            }
            catch
            {
                isInvokeFail = true;
            }
            return isInvokeFail;
        }
        /// <summary>
        /// 运行时间长度测试
        /// </summary>
        /// <param name="action">等待被测试的函数</param>
        /// <param name="times">执行的次数</param>
        /// <returns>运行的总时间</returns>
        public static TimeSpan ExecuteTime(Action action, int times)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < times; i++)
            {
                action.Invoke();
            }
            stopwatch.Stop();
            return TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds);
        }
        /// <summary>
        /// For循环器
        /// </summary>
        /// <param name="action">要循环的动作</param>
        /// <param name="times">循环的次数</param>
        public static void ForCirculator(Action action, int times)
        {
            for (int i = 0; i < times; i++)
            {
                action.Invoke();
            }
        }
    }
}
